package com.goldmantis.activemq.ch4;

import java.io.IOException;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.Topic;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.transport.TransportListener;

public class Consumer2 implements TransportListener{

    private static String brokerURL = "tcp://localhost:51616?trace=true";
    private static transient ConnectionFactory factory;
    private transient Connection connection;
    private transient Session session;
    
    public Consumer2() throws JMSException {
    	factory = new ActiveMQConnectionFactory(brokerURL);
    	connection = factory.createConnection();
    	connection.setClientID("topicConsumer2");
    	((ActiveMQConnection)connection).addTransportListener(this);;
        connection.start();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    }
    
    public void close() throws JMSException {
        if (connection != null) {
            connection.close();
        }
    }    
    
    public static void main(String[] args) throws JMSException {
    	Consumer2 consumer = new Consumer2();
		Destination destination = consumer.getSession().createTopic("STOCKS.1");
		MessageConsumer messageConsumer = consumer.getSession().createDurableSubscriber((Topic)destination,"test");
		messageConsumer.setMessageListener(new Listener());
    }
	
	public Session getSession() {
		return session;
	}
	
	@Override
	public void onCommand(Object command){
		System.out.println(command);
	}
	
	@Override
	public void onException(IOException error){
		System.out.println(error);
	}
	
	@Override
	public void transportInterupted(){
		System.out.println("transportResumed");
	}
	
	@Override
	public void transportResumed(){
		System.out.println("transportResumed");
	}	

}
